<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="反馈类型" prop="feedbackType">
        <el-select v-model="queryParams.feedbackType" placeholder="请选择反馈类型" clearable>
          <el-option v-for="item in feedbackTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="处理状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择处理状态" clearable>
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['user:feedback:edit']" type="success" plain icon="Check" @click="handleProcess">反馈处理</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['user:feedback:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
          >删除</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="反馈类型" align="center" prop="feedbackTypeName" width="100">
        <template #default="scope">
          <el-tag :type="getFeedbackTypeTag(scope.row.feedbackType)">
            {{ scope.row.feedbackTypeName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="反馈内容" align="center" prop="content" min-width="200" show-overflow-tooltip />
      <el-table-column label="联系方式" align="center" prop="contact" width="120" />
      <el-table-column label="反馈图片" align="center" width="120">
        <template #default="scope">
          <el-image
            v-if="scope.row.image"
            :src="scope.row.image"
            :preview-src-list="[scope.row.image]"
            :preview-teleported="true"
            fit="cover"
            class="feedback-image"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <div v-else class="image-slot">
            <el-icon><Picture /></el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="处理状态" align="center" prop="statusName" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="回复内容" align="center" prop="reply" min-width="200" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
          <el-button v-hasPermi="['user:feedback:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <!-- 添加或修改用户反馈对话框 -->
    <el-dialog v-model="open" :title="title" width="500px" append-to-body>
      <el-form ref="feedbackFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="反馈类型" prop="feedbackType">
          <el-select v-model="form.feedbackType" placeholder="请选择反馈类型">
            <el-option v-for="item in feedbackTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="反馈内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入反馈内容" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item v-if="form.feedbackType === 2" label="经纬度">
          <el-input v-model="coordinates" placeholder="经度,纬度" readonly>
            <template #append>
              <el-button @click="showMapDialog">选择位置</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择处理状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="回复内容" prop="reply">
          <el-input v-model="form.reply" type="textarea" placeholder="请输入回复内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 反馈处理对话框 -->
    <el-dialog v-model="processOpen" title="反馈处理" width="800px" append-to-body>
      <el-table v-loading="processLoading" :data="processList" style="width: 100%">
        <el-table-column label="反馈类型" align="center" prop="feedbackTypeName" />
        <el-table-column label="反馈内容" align="center" prop="content" :show-overflow-tooltip="true" />
        <el-table-column label="联系方式" align="center" prop="contact" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button link type="primary" @click="openNearbyDialog(scope.row)">处理维修</el-button>
            <el-button link type="success" @click="handleReply(scope.row)">简单回复</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 回复对话框 -->
    <el-dialog v-model="replyOpen" title="回复反馈" width="600px" append-to-body>
      <el-form ref="replyFormRef" :model="replyForm" :rules="replyRules" label-width="80px">
        <el-form-item label="反馈类型">
          <el-input :value="getFeedbackTypeLabel(replyForm.feedbackType)" readonly />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="replyForm.contact" placeholder="请输入联系方式" disabled />
        </el-form-item>
        <el-form-item label="反馈内容">
          <el-input v-model="replyForm.content" type="textarea" :rows="3" disabled />
        </el-form-item>
        <el-form-item label="反馈图片">
          <el-image
            v-if="replyForm.image"
            :src="replyForm.image"
            :preview-src-list="[replyForm.image]"
            :preview-teleported="true"
            fit="cover"
            class="feedback-image"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <div v-else class="image-slot">
            <el-icon><Picture /></el-icon>
          </div>
        </el-form-item>
        <el-form-item label="回复内容" prop="reply">
          <el-input v-model="replyForm.reply" type="textarea" :rows="3" placeholder="请输入回复内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitReply">确 定</el-button>
          <el-button @click="replyOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 附近设备选择对话框 -->
    <el-dialog v-model="nearbyDialog" title="选择附近售货机" width="900px" append-to-body @open="initNearbyMap" @close="destroyNearbyMap">
      <!-- 添加搜索范围控制 -->
      <div class="search-range-control" style="margin-bottom: 16px;">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-input-number
              v-model="searchRadius"
              :min="1"
              :max="50"
              :step="1"
              placeholder="搜索范围(km)"
              style="width: 100%;"
            />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="searchNearbyDevices" :loading="nearbyLoading">
              搜索设备
            </el-button>
          </el-col>
          <el-col :span="12">
            <el-alert
              v-if="nearbyDevices.length === 0 && !nearbyLoading"
              title="当前范围内未找到售货机，请尝试增加搜索范围"
              type="warning"
              :closable="false"
              show-icon
            />
          </el-col>
        </el-row>
      </div>

      <el-table
        ref="nearbyTableRef"
        v-loading="nearbyLoading"
        :data="nearbyDevices"
        :row-class-name="nearbyDeviceRowClass"
      >
        <el-table-column label="设备ID" prop="deviceId" width="120" />
        <el-table-column label="设备名称" prop="deviceName" />
        <el-table-column label="地址" prop="address" min-width="200" />
        <el-table-column label="距离(km)" prop="calcDistance" width="120">
          <template #default="scope">{{ scope.row.calcDistance }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button
              :type="(scope.row.deviceId + '') === selectedDeviceId ? 'success' : 'primary'"
              size="small"
              @click.stop="handleSelectDevice(scope.row)"
            >
              {{ (scope.row.deviceId + '') === selectedDeviceId ? '已选择' : '选择' }}
            </el-button>
            <el-button size="small" @click.stop="handleViewDeviceOnMap(scope.row, true)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="map-container" style="height: 350px; margin-top: 16px">
        <div ref="nearbyMapContainer" style="height: 100%; width: 100%"></div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="nearbyDialog = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmDevice">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 地图弹窗 -->
    <el-dialog v-model="mapDialogVisible" title="选择位置" width="800px" append-to-body destroy-on-close @close="handleMapDialogClose">
      <div class="map-search">
        <el-input v-model="searchKeyword" placeholder="请输入地址搜索" @keyup.enter="handleSearch">
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>
      <div class="map-tools">
        <el-button-group>
          <el-button :type="mapType === '3D' ? 'primary' : ''" @click="mapType = '3D'">3D</el-button>
          <el-button :type="mapType === '2D' ? 'primary' : ''" @click="mapType = '2D'">2D</el-button>
          <el-button :type="mapType === 'satellite' ? 'primary' : ''" @click="mapType = 'satellite'">卫星</el-button>
        </el-button-group>
        <el-button-group>
          <el-button @click="handleMapDialogClose">取消</el-button>
          <el-button type="primary" @click="handleConfirmMap">确定</el-button>
        </el-button-group>
      </div>
      <div class="map-container">
        <div ref="mapContainer" style="height: 100%; width: 100%"></div>
      </div>
    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-dialog v-model="viewOpen" title="反馈详情" width="900px" append-to-body>
      <el-form v-if="viewData" :model="viewData" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="反馈类型">
              <el-input :value="viewData?.feedbackTypeName" :readonly="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式">
              <el-input :value="viewData?.contact" :readonly="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="处理状态">
              <el-input :value="viewData?.statusName" :readonly="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="创建时间">
              <el-input :value="viewData?.createTime" :readonly="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-if="viewData?.feedbackType === 2" label="经纬度">
              <el-input
                v-if="viewData?.feedbackType === 2"
                :value="(viewData?.longitude || '') + ',' + (viewData?.latitude || '')"
                :readonly="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="反馈内容">
          <el-input :value="viewData?.content" type="textarea" :readonly="true" />
        </el-form-item>
        <el-form-item label="回复内容">
          <el-input :value="viewData?.reply" type="textarea" :readonly="true" />
        </el-form-item>
        <el-form-item label="反馈图片">
          <el-image
            v-if="viewData?.image"
            :src="viewData?.image"
            :preview-src-list="[viewData?.image]"
            fit="cover"
            style="width: 60px; height: 60px"
          />
        </el-form-item>
        <!-- 静态地图展示反馈位置 -->
        <el-form-item
          v-if="viewData?.feedbackType === 2 && isValidLngLat(viewData?.longitude, viewData?.latitude)"
          label="地图位置"
          class="big-map-item"
        >
          <div class="map-container big-map" style="height: 450px">
            <div ref="viewMapContainer" style="height: 100%; width: 100%"></div>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { UserFeedbackVO, UserFeedbackForm, UserFeedbackQuery } from '@/api/user/feedback/types';
import { getUserFeedbackList, getUserFeedback, addUserFeedback, updateUserFeedback, deleteUserFeedback } from '@/api/user/feedback';
import { ref, onMounted, nextTick, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listNearbyDevices } from '@/api/vending/es';
import { getDeviceDetail } from '@/api/vending/device';
import { useRouter } from 'vue-router';
import { geocode, regeocode, getLocationByIp } from '@/api/vending/map';
// import ImageUpload from '@/components/ImageUpload/index.vue';

// 反馈类型选项
const feedbackTypeOptions = [
  { value: 1, label: '功能建议' },
  { value: 2, label: '问题投诉' },
  { value: 3, label: '其他' }
];

// 处理状态选项
const statusOptions = [
  { value: 0, label: '未处理' },
  { value: 1, label: '处理中' },
  { value: 2, label: '已处理' }
];

// 获取状态标签
const getStatusLabel = (status: number) => {
  const option = statusOptions.find((item) => item.value === status);
  return option ? option.label : '';
};

// 获取状态类型
const getStatusType = (status: number) => {
  const typeMap = {
    0: 'info',
    1: 'warning',
    2: 'success'
  };
  return typeMap[status] || 'info';
};

// 获取反馈类型标签
const getFeedbackTypeLabel = (type: number) => {
  const option = feedbackTypeOptions.find((item) => item.value === type);
  return option ? option.label : '';
};

// 获取反馈类型标签样式
const getFeedbackTypeTag = (type: number) => {
  const typeMap = {
    1: 'success', // 功能建议
    2: 'danger', // 问题投诉
    3: 'info' // 其他
  };
  return typeMap[type] || 'info';
};

const loading = ref(true); // 遮罩层
const showSearch = ref(true); // 显示搜索条件
const ids = ref<number[]>([]); // 选中数组
const single = ref(true); // 非单个禁用
const multiple = ref(true); // 非多个禁用
const total = ref(0); // 总条数
const list = ref<UserFeedbackVO[]>([]); // 列表数据
const title = ref(''); // 弹出层标题
const open = ref(false); // 是否显示弹出层

// 反馈处理相关
const processOpen = ref(false); // 是否显示处理对话框
const processLoading = ref(false); // 处理列表加载状态
const processList = ref<UserFeedbackVO[]>([]); // 待处理列表

// 回复相关
const replyOpen = ref(false); // 是否显示回复对话框
const replyFormRef = ref();
const replyForm = ref({
  id: undefined as number | undefined,
  feedbackType: undefined as number | undefined,
  content: '',
  reply: '',
  contact: '',
  image: '',
  latitude: undefined as string | number | undefined,
  longitude: undefined as string | number | undefined,
  address: '',
  deviceId: undefined as number | undefined
});
// 存储当前回复的反馈数据，供地图等使用
let replyFeedbackData: any = null;

const replyRules = {
  feedbackType: [{ required: true, message: '反馈类型不能为空', trigger: 'change' }],
  contact: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
  reply: [{ required: true, message: '回复内容不能为空', trigger: 'blur' }]
};

const queryFormRef = ref();
const feedbackFormRef = ref();

const queryParams = ref<UserFeedbackQuery>({
  pageNum: 1,
  pageSize: 10,
  feedbackType: undefined,
  status: undefined
});

const form = ref<UserFeedbackForm>({
  feedbackType: undefined,
  content: '',
  contact: '',
  status: 0,
  reply: ''
});

const rules = ref({
  feedbackType: [{ required: true, message: '反馈类型不能为空', trigger: 'change' }],
  content: [{ required: true, message: '反馈内容不能为空', trigger: 'blur' }],
  contact: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '处理状态不能为空', trigger: 'change' }]
});

const router = useRouter();

// 附近设备选择相关
const nearbyDialog = ref(false);
const nearbyDevices = ref<any[]>([]);
const selectedDeviceId = ref<string | undefined>(undefined);
const pendingFeedback = ref<any>(null);
const nearbyLoading = ref(false); // 附近设备加载状态
const searchRadius = ref(5); // 搜索半径，默认5公里

// 地图相关变量
const mapDialogVisible = ref(false);
const mapType = ref('3D');
const showDetails = ref(false);
const searchKeyword = ref('');
const autoCompleteAddress = ref(true);
const mapLoaded = ref(false);
const originalAddress = ref('');
const originalLongitude = ref<string | number | undefined>();
const originalLatitude = ref<string | number | undefined>();
let map: any = null;
let marker: any = null;
let satelliteLayer: any = null;
const mapContainer = ref<HTMLElement>();

// 回复地图弹窗相关
const replyMapDialogVisible = ref(false);
const replyMapContainer = ref<HTMLElement>();
const replySearchKeyword = ref('');
let replyMap: any = null;
let replyMarker: any = null;

const coordinates = computed(() => {
  if (form.value.longitude && form.value.latitude) {
    return `${form.value.longitude},${form.value.latitude}`;
  }
  return '';
});

const preloadMapScript = () => {
  if (!window.AMap && !document.querySelector('script[src*="amap.com/maps"]')) {
    const script = document.createElement('script');
    script.src = `https://webapi.amap.com/maps?v=2.0&key=44f91bca5fc95f3e79620c2d50bbfaed&plugin=AMap.Geocoder,AMap.Geolocation,AMap.PlaceSearch,AMap.ToolBar,AMap.Scale,AMap.HawkEye,AMap.MapType`;
    script.async = true;
    script.onload = () => {
      mapLoaded.value = true;
    };
    document.head.appendChild(script);
  }
};

onMounted(() => {
  getList();
  preloadMapScript();
});

const showMapDialog = () => {
  mapDialogVisible.value = true;
  originalAddress.value = form.value.address || '';
  originalLongitude.value = form.value.longitude;
  originalLatitude.value = form.value.latitude;
  nextTick(() => {
    initMap();
  });
};

function handleSearch() {
  if (!searchKeyword.value) return;
  geocode(searchKeyword.value).then((response) => {
    if (response.data) {
      const { longitude, latitude, address } = response.data;
      form.value.longitude = longitude;
      form.value.latitude = latitude;
      form.value.address = address;
      updateMarker(longitude, latitude);
      map.setZoom(17);
    } else {
      ElMessage.error('未找到该地址');
    }
  });
}

function handleConfirmMap() {
  if (!form.value.longitude || !form.value.latitude) {
    ElMessage.error('请先选择位置');
    return;
  }
  if (autoCompleteAddress.value) {
    regeocode(Number(form.value.longitude), Number(form.value.latitude))
      .then((response) => {
        if (response.data) {
          form.value.address = response.data.formattedAddress || response.data.address;
          mapDialogVisible.value = false;
        } else {
          ElMessage.error('获取地址信息失败');
        }
      })
      .catch((error) => {
        ElMessage.error('获取地址信息失败：' + error.message);
      });
  } else {
    mapDialogVisible.value = false;
  }
}

function handleMapDialogClose() {
  mapDialogVisible.value = false;
  form.value.address = originalAddress.value;
  form.value.longitude = originalLongitude.value;
  form.value.latitude = originalLatitude.value;
  setTimeout(() => {
    if (map) {
      map.destroy();
      map = null;
    }
    if (marker) {
      marker.setMap(null);
      marker = null;
    }
    if (satelliteLayer) {
      map?.remove(satelliteLayer);
      satelliteLayer = null;
    }
    searchKeyword.value = '';
  }, 300);
}

function updateMarker(lng: number, lat: number) {
  if (!map) return;
  if (marker) marker.setMap(null);
  marker = new window.AMap.Marker({
    position: [lng, lat],
    map: map,
    animation: 'AMAP_ANIMATION_DROP',
    offset: new window.AMap.Pixel(-13, -30),
    icon: new window.AMap.Icon({
      size: new window.AMap.Size(25, 34),
      image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
      imageSize: new window.AMap.Size(25, 34)
    }),
    label: {
      content: '当前位置',
      direction: 'top',
      offset: new window.AMap.Pixel(10, 25)
    }
  });
  map.setCenter([lng, lat]);
  map.setZoom(17);
}

function initMap() {
  if (!mapContainer.value) return;
  if (satelliteLayer) {
    map.remove(satelliteLayer);
    satelliteLayer = null;
  }
  map = new window.AMap.Map(mapContainer.value, {
    zoom: 15,
    center: [116.397428, 39.90923],
    viewMode: '3D',
    pitch: 45,
    mapStyle: 'amap://styles/normal',
    features: ['bg', 'road', 'building', 'point'],
    dragEnable: true,
    zoomEnable: true,
    jogEnable: true,
    animateEnable: true,
    keyboardEnable: true,
    doubleClickZoom: true,
    scrollWheel: true,
    touchZoom: true,
    showLabel: true,
    layers: [
      new window.AMap.TileLayer(),
      new window.AMap.Buildings({
        zooms: [3, 20],
        opacity: 1,
        heightFactor: 1.5
      })
    ]
  });
  map.on('click', (e: any) => {
    const { lng, lat } = e.lnglat;
    form.value.longitude = lng;
    form.value.latitude = lat;
    updateMarker(lng, lat);
    regeocode(lng, lat).then((response) => {
      if (response.data) {
        form.value.address = response.data.address;
      }
    });
  });
  if (form.value.longitude && form.value.latitude) {
    updateMarker(Number(form.value.longitude), Number(form.value.latitude));
  }
}

/** 查询用户反馈列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await getUserFeedbackList(queryParams.value);
    console.log(res);
    // 处理反馈类型名称
    list.value = res.rows.map((item) => ({
      ...item,
      feedbackTypeName: getFeedbackTypeLabel(item.feedbackType)
    }));
    console.log(list.value);
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 查询待处理反馈列表 */
const getProcessList = async () => {
  processLoading.value = true;
  try {
    const res = await getUserFeedbackList({
      pageNum: 1,
      pageSize: 10,
      status: 0
    });
    processList.value = res.rows.map((item) => ({
      ...item,
      feedbackTypeName: getFeedbackTypeLabel(item.feedbackType)
    }));
  } finally {
    processLoading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
};

/** 表单重置 */
const reset = () => {
  form.value = {
    feedbackType: undefined,
    content: '',
    contact: '',
    status: 0,
    reply: ''
  };
  feedbackFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: UserFeedbackVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加用户反馈';
};

/** 查看详情弹窗 */
const viewOpen = ref(false);
const viewData = ref<UserFeedbackVO | null>(null);
const handleView = async (row: UserFeedbackVO) => {
  const res = await getUserFeedback(row.id);
  let data = res.data;
  // 补全反馈类型/状态名称
  if (!data.feedbackTypeName) data.feedbackTypeName = getFeedbackTypeLabel(data.feedbackType);
  if (!data.statusName) data.statusName = getStatusLabel(data.status);
  // 补全用户信息
  if (data.userBase) {
    data.userName = data.userBase.username || data.userName;
    data.avatar = data.userBase.avatar || data.avatar;
  }
  // 经纬度容错
  if (!data.longitude || isNaN(Number(data.longitude))) data.longitude = undefined;
  if (!data.latitude || isNaN(Number(data.latitude))) data.latitude = undefined;
  viewData.value = data;
  viewOpen.value = true;
};

/** 提交按钮 */
const submitForm = async () => {
  feedbackFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (form.value.id) {
          await updateUserFeedback(form.value);
          ElMessage.success('修改成功');
        } else {
          await addUserFeedback(form.value);
          ElMessage.success('新增成功');
        }
        open.value = false;
        getList();
      } catch (error) {
        console.error(error);
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: UserFeedbackVO) => {
  const feedbackIds = row?.id ? [row.id] : ids.value;
  try {
    await ElMessageBox.confirm('是否确认删除用户反馈编号为"' + feedbackIds + '"的数据项?');
    await deleteUserFeedback(feedbackIds);
    getList();
    ElMessage.success('删除成功');
  } catch (error) {
    console.error(error);
  }
};

/** 反馈处理按钮操作 */
const handleProcess = () => {
  processOpen.value = true;
  getProcessList();
};

/** 回复按钮操作 */
const handleReply = (row: UserFeedbackVO) => {
  // 只弹出简单回复对话框，不再弹附近售货机
  replyFeedbackData = JSON.parse(JSON.stringify(row));
  replyForm.value = {
    id: row.id,
    feedbackType: row.feedbackType,
    content: row.content,
    reply: '',
    contact: row.contact,
    image: row.image,
    latitude: row.latitude,
    longitude: row.longitude,
    address: row.address,
    deviceId: row.deviceId
  };
  replyOpen.value = true;
};

/** 提交回复 */
const submitReply = async () => {
  replyFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await updateUserFeedback({
          id: replyForm.value.id,
          feedbackType: replyForm.value.feedbackType,
          content: replyForm.value.content,
          contact: replyForm.value.contact,
          status: 2,
          reply: replyForm.value.reply
        });
        ElMessage.success('回复成功');
        replyOpen.value = false;
        getProcessList();
        getList();
      } catch (error) {
        console.error(error);
      }
    }
  });
};

async function openNearbyDialog(feedback) {
  // 保证每次弹窗都存主点数据
  replyFeedbackData = JSON.parse(JSON.stringify(feedback));
  nearbyDialog.value = true;
  // 新增：如果有deviceId，默认选中
  if (feedback.deviceId) {
    selectedDeviceId.value = feedback.deviceId + '';
  } else {
    selectedDeviceId.value = undefined;
  }
  pendingFeedback.value = feedback;
  // 重置搜索半径为默认值
  searchRadius.value = 5;
  // 清空之前的设备列表
  nearbyDevices.value = [];
}

/** 搜索附近设备 */
const searchNearbyDevices = async () => {
  if (!replyFeedbackData || !isValidLngLat(Number(replyFeedbackData.longitude), Number(replyFeedbackData.latitude))) {
    ElMessage.error('反馈位置信息无效，无法搜索附近设备');
    return;
  }

  if (!searchRadius.value || searchRadius.value < 1) {
    ElMessage.error('请输入有效的搜索范围');
    return;
  }

  nearbyLoading.value = true;
  try {
    const res = await listNearbyDevices(Number(replyFeedbackData.longitude), Number(replyFeedbackData.latitude), searchRadius.value);
    let devices = res.data || [];

    if (devices.length === 0) {
      ElMessage.warning(`在${searchRadius.value}公里范围内未找到售货机`);
      nearbyDevices.value = [];
      return;
    }

    // 兼容多种经纬度字段并强制类型安全
    devices = devices.map((d) => {
      const lng = Number(d.longitude ?? d.lon ?? d.location?.longitude ?? d.location?.lon);
      const lat = Number(d.latitude ?? d.lat ?? d.location?.latitude ?? d.location?.lat);
      return {
        ...d,
        longitude: lng,
        latitude: lat,
        address: d.address || d.installAddress || d.location?.address || d.location || '',
        calcDistance:
          isValidLngLat(Number(replyFeedbackData?.longitude), Number(replyFeedbackData?.latitude)) && isValidLngLat(lng, lat)
            ? getDistance(Number(replyFeedbackData?.latitude), Number(replyFeedbackData?.longitude), lat, lng)
            : ''
      };
    });

    // 只保留经纬度有效的
    devices = devices.filter((d) => isValidLngLat(d.longitude, d.latitude));

    // 批量查详情
    const detailPromises = devices.map((d) =>
      getDeviceDetail(d.deviceId, 1)
        .then((res) => ({ ...d, ...res.data }))
        .catch(() => d)
    );
    devices = await Promise.all(detailPromises);

    // 动态补全address和calcDistance，全部补全后再赋值
    await Promise.all(
      devices.map(async (dev) => {
        // 地址补全
        if (isValidLngLat(dev.longitude, dev.latitude)) {
          try {
            const res = await regeocode(dev.longitude, dev.latitude);
            dev.address = res.data?.address || res.data?.formattedAddress || '';
          } catch (e) {
            dev.address = '';
          }
        }
        // 距离补全
        if ((!dev.calcDistance || isNaN(dev.calcDistance)) && isValidLngLat(dev.longitude, dev.latitude)) {
          try {
            dev.calcDistance = getDistance(Number(replyFeedbackData?.latitude), Number(replyFeedbackData?.longitude), dev.latitude, dev.longitude);
          } catch (e) {
            dev.calcDistance = '';
          }
        }
      })
    );

    nearbyDevices.value = devices;
    ElMessage.success(`找到${devices.length}台售货机`);

    // 更新地图上的marker
    updateNearbyMapMarkers();
  } catch (e) {
    console.error('搜索附近设备失败:', e);
    ElMessage.error('获取附近售货机失败');
    nearbyDevices.value = [];
  } finally {
    nearbyLoading.value = false;
  }
};

/** 更新附近设备地图标记 */
const updateNearbyMapMarkers = () => {
  if (!nearbyMap) return;

  // 清理旧marker
  nearbyMapMarkers.forEach((m) => m.setMap(null));
  nearbyMapMarkers = [];

  // 主点marker
  try {
    const mainLng = Number(replyFeedbackData?.longitude);
    const mainLat = Number(replyFeedbackData?.latitude);
    if (isValidLngLat(mainLng, mainLat)) {
      const mainMarker = new window.AMap.Marker({
        position: [mainLng, mainLat],
        map: nearbyMap,
        title: '反馈位置',
        icon: new window.AMap.Icon({
          size: new window.AMap.Size(24, 30),
          image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
          imageSize: new window.AMap.Size(24, 30)
        })
      });
      nearbyMapMarkers.push(mainMarker);
    }
  } catch (e) {
    console.error('主点marker渲染失败', replyFeedbackData, e);
  }

  // 附近售货机marker
  if (Array.isArray(nearbyDevices.value)) {
    nearbyDevices.value.forEach((dev) => {
      const devLng = Number(dev.longitude ?? dev.lon);
      const devLat = Number(dev.latitude ?? dev.lat);
      if (isValidLngLat(devLng, devLat)) {
        try {
          const marker = new window.AMap.Marker({
            position: [devLng, devLat],
            map: nearbyMap,
            title: dev.deviceName || dev.deviceNo || '售货机',
            icon: new window.AMap.Icon({
              size: new window.AMap.Size(20, 27),
              image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
              imageSize: new window.AMap.Size(20, 27)
            })
          });
          marker.on('click', async () => {
            const infoWindow = new window.AMap.InfoWindow({
              content: `<div style='min-width:220px;'>加载中...</div>`,
              offset: new window.AMap.Pixel(0, -20)
            });
            infoWindow.open(nearbyMap, [devLng, devLat]);
            try {
              const res = await getDeviceDetail(dev.deviceId, 1);
              const detail = (res.data || {}) as any;
              const infoContent = `
                <div style='min-width:220px;'>
                    <div><b>设备名称：</b>${detail.deviceName || ''}</div>
                    <div><b>设备编号：</b>${detail.deviceNo || ''}</div>
                    <div><b>类型：</b>${detail.deviceType?.typeName || ''}</div>
                    <div><b>通道数：</b>${detail.channelCount || ''}</div>
                    <div><b>距离反馈点：</b>${dev.calcDistance || ''} km</div>
                    <div style='color:#888;font-size:12px;margin-top:4px;'>创建：${detail.createTime || ''}</div>
                  </div>
              `;
              infoWindow.setContent(infoContent);
            } catch (e) {
              infoWindow.setContent(`<div style='color:red;'>设备详情获取失败</div>`);
            }
          });
          nearbyMapMarkers.push(marker);
        } catch (e) {
          console.error('设备点marker渲染失败', dev, devLng, devLat, e);
        }
      } else {
        console.warn('设备点渲染被跳过，经纬度无效', dev);
      }
    });
  }
};

const nearbyTableRef = ref();

function handleSelectDevice(device) {
  // 如果当前已选中，再次点击则取消选择
  if (selectedDeviceId.value === (device.deviceId + '')) {
    selectedDeviceId.value = undefined;
    ElMessage.info('已取消选择');
    return;
  }
  // 选择新设备
  selectedDeviceId.value = device.deviceId + '';
  if (nearbyTableRef.value) {
    nearbyTableRef.value.setCurrentRow(device);
  }
  ElMessage.success('已选择售货机：' + (device.deviceName || device.deviceId));
}

function handleConfirmDevice() {
  if (!selectedDeviceId.value) {
    ElMessage.warning('请选择售货机');
    return;
  }
  // 新增：先更新反馈的 deviceId 字段
  if (pendingFeedback.value && pendingFeedback.value.id) {
    updateUserFeedback({
      id: pendingFeedback.value.id,
      feedbackType: pendingFeedback.value.feedbackType,
      content: pendingFeedback.value.content,
      contact: pendingFeedback.value.contact,
      status: pendingFeedback.value.status,
      reply: pendingFeedback.value.reply,
      longitude: pendingFeedback.value.longitude,
      latitude: pendingFeedback.value.latitude,
      address: pendingFeedback.value.address,
      deviceId: parseInt(selectedDeviceId.value)
    }).then(() => {
      // 跳转到维护单页面并带参数
      router.push({
        path: '/vending/maintenanceEdit/index',
        query: {
          type: 'add',
          deviceId: selectedDeviceId.value,
          contact: pendingFeedback.value.contact,
          content: pendingFeedback.value.content,
          image: pendingFeedback.value.image,
          maintenanceType: 2 // 故障维修
        }
      });
      nearbyDialog.value = false;
    });
  } else {
    // 跳转到维护单页面并带参数
    router.push({
      path: '/vending/maintenanceEdit/index',
      query: {
        type: 'add',
        deviceId: selectedDeviceId.value,
        contact: pendingFeedback.value.contact,
        content: pendingFeedback.value.content,
        image: pendingFeedback.value.image,
        maintenanceType: 2 // 故障维修
      }
    });
    nearbyDialog.value = false;
  }
}

// 计算两点经纬度距离（单位：km）
function getDistance(lat1, lng1, lat2, lng2) {
  function toRad(d) {
    return (d * Math.PI) / 180;
  }
  const R = 6371; // 地球半径km
  const dLat = toRad(lat2 - lat1);
  const dLng = toRad(lng2 - lng1);
  const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return Math.round(R * c * 1000) / 1000; // 保留3位小数
}

// 查看详情地图和附近售货机
const viewMapContainer = ref<HTMLElement>();
let viewMap = null;
let viewMarkers = [];

const viewNearbyDevices = ref<any[]>([]);
// 兼容ES返回的lat/lon字段，获取附近售货机
async function updateViewNearbyDevices() {
  console.log('viewData:', viewData.value);
  if (!viewData.value || !isValidLngLat(Number(viewData.value.longitude), Number(viewData.value.latitude))) return;
  // 用ES接口获取附近售货机
  const res = await listNearbyDevices(Number(viewData.value.longitude), Number(viewData.value.latitude), 20);
  console.log('ES listNearbyDevices接口返回：', res);
  let devices = res.data || [];
  // 打印原始设备对象
  console.log('原始设备对象:', devices);
  // 兼容多种经纬度字段
  devices = devices.map((d) => {
    const lng = d.longitude ?? d.lon ?? d.location?.longitude ?? d.location?.lon;
    const lat = d.latitude ?? d.lat ?? d.location?.latitude ?? d.location?.lat;
    return {
      ...d,
      longitude: lng,
      latitude: lat,
      address: d.address || d.installAddress || d.location?.address || d.location || '',
      calcDistance:
        isValidLngLat(Number(viewData.value.longitude), Number(viewData.value.latitude)) && isValidLngLat(Number(lng), Number(lat))
          ? getDistance(Number(viewData.value.latitude), Number(viewData.value.longitude), Number(lat), Number(lng))
          : ''
    };
  });
  // 只保留经纬度有效的
  devices = devices.filter((d) => isValidLngLat(Number(d.longitude), Number(d.latitude)));
  console.log('nearby devices after filter:', devices);
  viewNearbyDevices.value = devices;
}

watch(viewOpen, (val) => {
  if (val && viewData.value && isValidLngLat(Number(viewData.value.longitude), Number(viewData.value.latitude))) {
    nextTick(async () => {
      if (!viewMapContainer.value) return;
      // 检查容器尺寸
      const w = viewMapContainer.value.offsetWidth;
      const h = viewMapContainer.value.offsetHeight;
      console.log('地图容器尺寸', w, h);
      if (!w || !h) {
        console.error('地图容器尺寸为0，无法渲染地图');
        return;
      }
      const lng = Number(viewData.value.longitude);
      const lat = Number(viewData.value.latitude);
      if (!isValidLngLat(lng, lat)) {
        console.warn('主反馈点经纬度无效', lng, lat, viewData.value);
        return;
      }
      // 只初始化一次地图
      if (!viewMap) {
        viewMap = new window.AMap.Map(viewMapContainer.value, {
          zoom: 15,
          center: [lng, lat],
          viewMode: '3D',
          pitch: 45,
          mapStyle: 'amap://styles/normal',
          features: ['bg', 'road', 'building', 'point']
        });
      } else {
        viewMap.setCenter([lng, lat]);
        viewMap.setZoom(15);
      }
      // 清理旧marker
      viewMarkers.forEach((m) => m.setMap(null));
      viewMarkers = [];
      // 主点marker
      try {
        if (isNaN(lng) || isNaN(lat)) {
          console.error('主点marker渲染前发现NaN', lng, lat, viewData.value);
          return;
        }
        const mainMarker = new window.AMap.Marker({
          position: [lng, lat],
          map: viewMap,
          title: '反馈位置',
          icon: new window.AMap.Icon({
            size: new window.AMap.Size(24, 30),
            image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
            imageSize: new window.AMap.Size(24, 30)
          })
        });
        viewMarkers.push(mainMarker);
      } catch (e) {
        console.error('主点marker渲染失败', lng, lat, viewData.value, e);
      }
      // 异步获取附近售货机并动态添加marker
      await updateViewNearbyDevices();
      console.log('viewNearbyDevices.value', viewNearbyDevices.value);
      if (Array.isArray(viewNearbyDevices.value)) {
        viewNearbyDevices.value.forEach((dev) => {
          const devLng = Number(dev.longitude ?? dev.lon);
          const devLat = Number(dev.latitude ?? dev.lat);
          if (isValidLngLat(devLng, devLat)) {
            try {
              const marker = new window.AMap.Marker({
                position: [devLng, devLat],
                map: viewMap,
                title: dev.deviceName || dev.deviceNo || '售货机',
                icon: new window.AMap.Icon({
                  size: new window.AMap.Size(20, 27),
                  image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
                  imageSize: new window.AMap.Size(20, 27)
                })
              });
              // 点击marker弹出详情（动态查详情）
              marker.on('click', async () => {
                const infoWindow = new window.AMap.InfoWindow({
                  content: `<div style='min-width:220px;'>加载中...</div>`,
                  offset: new window.AMap.Pixel(0, -20)
                });
                infoWindow.open(viewMap, [devLng, devLat]);
                try {
                  const res = await getDeviceDetail(dev.deviceId, 1);
                  console.log(res);
                  const detail = (res.data || {}) as any;
                  // 通道/库存信息
                  let stockHtml = '';
                  const infoContent = `
                    <div style='min-width:220px;'>
                      <div><b>设备名称：</b>${detail.deviceName || ''}</div>
                      <div><b>设备编号：</b>${detail.deviceNo || ''}</div>
                      <div><b>类型：</b>${detail.deviceType?.typeName || ''}</div>
                      <div><b>通道数：</b>${detail.channelCount || ''}</div>
                      <div><b>距离反馈点：</b>${dev.calcDistance || ''} km</div>
                      <div style='color:#888;font-size:12px;margin-top:4px;'>创建：${detail.createTime || ''}</div>
                    </div>
                  `;
                  infoWindow.setContent(infoContent);
                } catch (e) {
                  infoWindow.setContent(`<div style='color:red;'>设备详情获取失败</div>`);
                }
              });
              viewMarkers.push(marker);
            } catch (e) {
              console.error('设备点marker渲染失败', dev, devLng, devLat, e);
            }
          } else {
            console.warn('设备点渲染被跳过，经纬度无效', dev);
          }
        });
      }
    });
  } else {
    // 销毁地图和marker
    if (viewMap) {
      viewMap.destroy();
      viewMap = null;
    }
    viewMarkers.forEach((m) => m.setMap(null));
    viewMarkers = [];
    viewNearbyDevices.value = [];
  }
});

function showReplyMapDialog() {
  replyMapDialogVisible.value = true;
  nextTick(() => {
    if (!replyMapContainer.value) return;
    let lng = Number(replyForm.value.longitude);
    let lat = Number(replyForm.value.latitude);
    if (isNaN(lng)) lng = 116.397428;
    if (isNaN(lat)) lat = 39.90923;
    replyMap = new window.AMap.Map(replyMapContainer.value, {
      zoom: 15,
      center: [lng, lat],
      viewMode: '3D',
      pitch: 45,
      mapStyle: 'amap://styles/normal',
      features: ['bg', 'road', 'building', 'point']
    });
    if (!isNaN(lng) && !isNaN(lat)) {
      replyMarker = new window.AMap.Marker({
        position: [lng, lat],
        map: replyMap
      });
      replyMap.setCenter([lng, lat]);
    }
    replyMap.on('click', (e: any) => {
      const { lng, lat } = e.lnglat;
      replyForm.value.longitude = lng;
      replyForm.value.latitude = lat;
      if (replyMarker) replyMarker.setMap(null);
      replyMarker = new window.AMap.Marker({ position: [lng, lat], map: replyMap });
      regeocode(lng, lat).then((response) => {
        if (response.data) replyForm.value.address = response.data.address;
      });
    });
  });
}
function handleReplyMapDialogClose() {
  replyMapDialogVisible.value = false;
  setTimeout(() => {
    if (replyMap) {
      replyMap.destroy();
      replyMap = null;
    }
    if (replyMarker) {
      replyMarker.setMap(null);
      replyMarker = null;
    }
    replySearchKeyword.value = '';
  }, 300);
}
function handleReplyMapSearch() {
  if (!replySearchKeyword.value) return;
  geocode(replySearchKeyword.value).then((response) => {
    if (response.data) {
      const { longitude, latitude, address } = response.data;
      replyForm.value.longitude = longitude;
      replyForm.value.latitude = latitude;
      replyForm.value.address = address;
      if (replyMarker) replyMarker.setMap(null);
      replyMarker = new window.AMap.Marker({ position: [longitude, latitude], map: replyMap });
      replyMap.setCenter([longitude, latitude]);
      replyMap.setZoom(17);
    } else {
      ElMessage.error('未找到该地址');
    }
  });
}
function confirmReplyMap() {}

// 工具函数：校验经纬度
function isValidLngLat(lng, lat) {
  return lng !== undefined && lat !== undefined && !isNaN(Number(lng)) && !isNaN(Number(lat));
}

// 地图联动查看售货机
function handleViewDeviceOnMap(device, isNearbyDialog = false) {
  // 如果是附近弹窗里的地图，操作nearbyMap，否则操作主viewMap
  const map = isNearbyDialog ? nearbyMap : viewMap;
  if (isNearbyDialog) nearbyDialog.value = false;
  nextTick(() => {
    if (!map) return;
    const lng = Number(device.longitude ?? device.lon ?? device.location?.longitude ?? device.location?.lon);
    const lat = Number(device.latitude ?? device.lat ?? device.location?.latitude ?? device.location?.lat);
    if (!isValidLngLat(lng, lat)) return;
    map.setCenter([lng, lat]);
    map.setZoom(17);
    const infoWindow = new window.AMap.InfoWindow({
      content: `<div style='min-width:220px;'>加载中...</div>`,
      offset: new window.AMap.Pixel(0, -20)
    });
    infoWindow.open(map, [lng, lat]);
    getDeviceDetail(device.deviceId, 1)
      .then((res) => {
        const detail = (res.data || {}) as any;
        let imgHtml = '';
        if (detail.imgUrl) {
          imgHtml = `<div style="text-align:center;margin-bottom:6px;"><img src='${detail.imgUrl}' style='max-width:80px;max-height:60px;border-radius:4px;' /></div>`;
        }
        let stockHtml = '';
        if (Array.isArray(detail.deviceStock) && detail.deviceStock.length > 0) {
          stockHtml =
            `<div><b>库存：</b><ul style='padding-left:18px;margin:0;'>` +
            detail.deviceStock
              .slice(0, 3)
              .map((s) => `<li>通道${s.channelId}：${s.stockQuantity}/${s.maxQuantity}</li>`)
              .join('') +
            (detail.deviceStock.length > 3 ? '<li>...</li>' : '') +
            `</ul></div>`;
        }
        const infoContent = `
         <div style='min-width:220px;'>
                      <div><b>设备名称：</b>${detail.deviceName || ''}</div>
                      <div><b>设备编号：</b>${detail.deviceNo || ''}</div>
                      <div><b>类型：</b>${detail.deviceType?.typeName || ''}</div>
                      <div><b>通道数：</b>${detail.channelCount || ''}</div>
                      <div><b>距离反馈点：</b>${device.calcDistance || ''} km</div>
                      <div style='color:#888;font-size:12px;margin-top:4px;'>创建：${detail.createTime || ''}</div>
                    </div>
      `;
        infoWindow.setContent(infoContent);
      })
      .catch(() => {
        infoWindow.setContent(`<div style='color:red;'>设备详情获取失败</div>`);
      });
  });
}

let nearbyMap = null;
let nearbyMapMarkers = [];
const nearbyMapContainer = ref();

function initNearbyMap() {
  nextTick(async () => {
    if (!nearbyMapContainer.value) return;
    if (!nearbyMap) {
      let center = [113.055527, 25.788275];
      const mainLng = Number(replyFeedbackData?.longitude);
      const mainLat = Number(replyFeedbackData?.latitude);
      if (isValidLngLat(mainLng, mainLat)) {
        center = [mainLng, mainLat];
      }
      nearbyMap = new window.AMap.Map(nearbyMapContainer.value, {
        zoom: 15,
        center,
        viewMode: '3D',
        pitch: 45,
        mapStyle: 'amap://styles/normal',
        features: ['bg', 'road', 'building', 'point']
      });
    }

    // 只渲染主点marker，设备marker由searchNearbyDevices函数处理
    nearbyMapMarkers.forEach((m) => m.setMap(null));
    nearbyMapMarkers = [];

    // 主点marker
    try {
      const mainLng = Number(replyFeedbackData?.longitude);
      const mainLat = Number(replyFeedbackData?.latitude);
      if (isValidLngLat(mainLng, mainLat)) {
        const mainMarker = new window.AMap.Marker({
          position: [mainLng, mainLat],
          map: nearbyMap,
          title: '反馈位置',
          icon: new window.AMap.Icon({
            size: new window.AMap.Size(24, 30),
            image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
            imageSize: new window.AMap.Size(24, 30)
          })
        });
        nearbyMapMarkers.push(mainMarker);
      }
    } catch (e) {
      console.error('主点marker渲染失败', replyFeedbackData, e);
    }
  });
}

function destroyNearbyMap() {
  if (nearbyMap) {
    nearbyMap.destroy();
    nearbyMap = null;
  }
  nearbyMapMarkers.forEach((m) => m.setMap(null));
  nearbyMapMarkers = [];
}

function nearbyDeviceRowClass(row: any) {
  return (row.row.deviceId + '') === selectedDeviceId.value ? 'highlight-row' : '';
}
</script>

<style lang="scss" scoped>
.feedback-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
  border: 1px solid var(--el-border-color-light);
  transition: all 0.3s;
  cursor: pointer;

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

.image-slot {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-secondary);
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
  border: 1px solid var(--el-border-color-light);

  .el-icon {
    font-size: 24px;
  }
}

// 地图相关样式
.map-search {
  margin-bottom: 16px;
}

.map-tools {
  margin-bottom: 16px;
  display: flex;
  gap: 16px;
}

.map-container {
  height: 400px;
  min-height: 300px;
  &.big-map {
    height: 450px !important;
    min-height: 400px !important;
  }
  width: 100% !important;
  border-radius: 8px;
  overflow: hidden;
}

// 优化详情弹窗表单布局
.el-dialog__body {
  padding: 32px 32px 24px 32px !important;
}

.big-map-item {
  .el-form-item__label {
    line-height: 1.2;
    font-size: 16px;
    font-weight: bold;
  }
}

.highlight-row {
  background: #e6f7ff !important;
}

// 搜索范围控制样式
.search-range-control {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid var(--el-border-color-light);

  .el-row {
    align-items: center;
  }

  .el-input-number {
    .el-input__wrapper {
      border-radius: 6px;
    }
  }

  .el-button {
    border-radius: 6px;
  }
}
</style>
